import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import { ProFormText } from '@ant-design/pro-components';
import { LockOutlined } from '@ant-design/icons';
import { createStyles } from 'antd-style';
import { Form } from 'antd';
import { handleAlphanumericPasswordInput } from '@/components/business/index';

// 生成随机验证码
const generateCaptcha = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let captcha = '';
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return captcha;
};

// 绘制验证码图片
const drawCaptcha = (text: string) => {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  if (!ctx) return '';

  canvas.width = 120;
  canvas.height = 40;

  // 背景色
  ctx.fillStyle = '#f5f5f5';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  // 干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
    ctx.beginPath();
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI);
    ctx.fill();
  }

  // 绘制文字
  ctx.font = 'bold 24px Arial';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';

  text.split('').forEach((char, i) => {
    ctx.fillStyle = `rgb(${Math.random() * 100 + 50},${Math.random() * 100 + 50},${Math.random() * 100 + 50})`;
    ctx.save();
    ctx.translate(25 + i * 20, canvas.height / 2);
    ctx.rotate((Math.random() - 0.5) * 0.4);
    ctx.fillText(char, 0, 0);
    ctx.restore();
  });

  return canvas.toDataURL('image/png');
};

// 组件样式
const useStyles = createStyles(({ token }) => {
  return {
    captchaContainer: {
      display: 'flex',
      gap: 12,
      alignItems: 'flex-start',
      width: '100%',
    },
    captchaInputWrap: {
      flex: 1,
      minWidth: 0,
    },
    captchaImageWrap: {
      flexShrink: 0,
      display: 'flex',
      alignItems: 'center',
      height: 40,
    },
    captchaImage: {
      width: 120,
      height: 40,
      cursor: 'pointer',
      borderRadius: 4,
      border: `1px solid ${token.colorBorder}`,
      transition: 'all 0.2s',
      '&:hover': {
        opacity: 0.8,
        borderColor: token.colorPrimary,
      },
    },
    errorText: {
      color: token.colorError,
      fontSize: 12,
      marginTop: 4,
      marginBottom: 0,
    },
  };
});

// 组件属性定义
interface CaptchaInputProps {
  // 定义属性类型
  form: Form.FormInstance;
  captchaError: string;
  onCaptchaErrorChange: (error: string) => void;
  onRefreshCaptcha?: () => void;
  onCaptchaSuccess?: () => void;
}

export interface CaptchaInputRef {
  validateCaptcha: (inputValue?: string) => boolean;
  refreshCaptcha: () => void;
}

// 验证码输入组件
const CaptchaInput = forwardRef<CaptchaInputRef, CaptchaInputProps>(({
  // 属性定义
  form,
  captchaError,
  onCaptchaErrorChange,
  onRefreshCaptcha,
  onCaptchaSuccess,
}, ref) => {
  const [captchaText, setCaptchaText] = useState('');
  const [captchaImage, setCaptchaImage] = useState('');
  const { styles } = useStyles();
  const captchaVerified = useRef(false);
  const isManualValidating = useRef(false);

  // 刷新验证码
  const refreshCaptcha = () => {
    const text = generateCaptcha();
    setCaptchaText(text);
    setCaptchaImage(drawCaptcha(text));
    onCaptchaErrorChange('');
    captchaVerified.current = false;
    form.setFieldsValue({ captcha: '' });
    onRefreshCaptcha?.();
  };

  // 验证验证码
  const validateCaptcha = (inputValue?: string): boolean => {
    if (isManualValidating.current) return false;
    isManualValidating.current = true;

    try {
      let valueToValidate = inputValue || form.getFieldValue('captcha') || '';

      if (!valueToValidate) {
        form.setFields([{ name: 'captcha', errors: ['请输入验证码！'] }]);
        captchaVerified.current = false;
        return false;
      }

      if (valueToValidate.length !== 4) {
        form.setFields([{ name: 'captcha', errors: ['验证码长度为4位!'] }]);
        captchaVerified.current = false;
        return false;
      }

      //在比对时转大写
      if (valueToValidate.toUpperCase() !== captchaText.toUpperCase()) {
        form.setFields([{ name: 'captcha', errors: ['验证码错误，请重新输入'] }]);
        captchaVerified.current = false;
        return false;
      }

      form.setFields([{ name: 'captcha', errors: [] }]);
      captchaVerified.current = true;
      onCaptchaSuccess?.();
      return true;
    } finally {
      setTimeout(() => {
        isManualValidating.current = false;
      }, 100);
    }
  };

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    validateCaptcha,
    refreshCaptcha,
  }));

  // 初始化验证码
  useEffect(() => {
    refreshCaptcha();
  }, []);

  // 简化的验证规则
  const validateCaptchaRule = async (_: any, value: string) => {
    if (!value) {
      throw new Error('请输入验证码！');
    }

    if (value.length !== 4) {
      throw new Error('验证码长度为4位！');
    }

    return Promise.resolve();
  };

  // 实时验证
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    form.setFieldsValue({ captcha: value }); // 保存输入值

    if (captchaError) {
      onCaptchaErrorChange('');
    }

    if (value.length === 4) {
      setTimeout(() => {
        validateCaptcha(value);
      }, 0);
    } else {
      captchaVerified.current = false;
    }
  };

  // 处理图片点击刷新
  const handleImageClick = () => {
    refreshCaptcha();
    onCaptchaErrorChange('');
    form.setFieldsValue({ captcha: '' });
    captchaVerified.current = false;
  };

  return (
    <div>
      <div className={styles.captchaContainer}>
        <div className={styles.captchaInputWrap}>
          <ProFormText
            name="captcha"
            fieldProps={{
              size: 'large',
              prefix: <LockOutlined />,
              maxLength: 4,
              onChange: (e) => {
                handleAlphanumericPasswordInput(form, 'captcha', e);
                handleInputChange(e); // 传递原始输入事件
              },
              onPaste: (e) => {
                handleAlphanumericPasswordInput(form, 'captcha', e);
              },
              style: {},
              onKeyDown: (e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                  form.validateFields(['captcha']).then(() => {
                    form.submit();
                  });
                }
              },
            }}
            placeholder="请输入验证码"
            rules={[
              { validator: validateCaptchaRule },
            ]}
          />
        </div>
        <div className={styles.captchaImageWrap}>
          <img
            src={captchaImage}
            alt="验证码"
            className={styles.captchaImage}
            onClick={handleImageClick}
            title="点击刷新验证码"
            onError={(e) => {
              const target = e.target as HTMLImageElement;
              target.src = drawCaptcha(captchaText);
            }}
          />
        </div>
      </div>
      {captchaError && <div className={styles.errorText}>{captchaError}</div>}
    </div>
  );
});

export default CaptchaInput;